<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true"><block slot="backText">{{task.taskName}}</block><block slot="content"></block></cu-custom>
		
		<scroll-view scroll-x class="bg-white nav" scroll-with-animation :scroll-left="scrollLeft">
		   <view class="propertyBox">
		     <view class="cu-item" :class="index == TabCur ? 'text-green cur' : ''" v-for="(item, index) in modules" :key="index" @tap="tabSelect" :data-id="index">
		       {{ item.name }}
		     </view>
		   </view>
		 </scroll-view>
		
		<view v-model="task" v-if="TabCur === 0" >
			<view class="bg-white" style="margin-bottom: 5px;">
				<view class="item padding round" style="border: 6px solid white;padding: 10rpx;">
					<view class="cu-form-group">
						<input type="text" v-model="task.taskName" style="size: 20px;" :disabled="isCreatStaff()"/>
					</view>
					<view class="cu-form-group" @tap="selectAlignment" v-if="showAlignment">
						<view class="cuIcon-activityfill" style="size: 20px;" >对标关键结果</view>
						<text v-model="okr.name" style="size: 20px;" >{{ okr.name ? okr.name : '请选择对标关键结果' }}</text>
					</view>
					<!-- 负责人 -->
					<view class="cu-form-group" :class="menuArrow ? 'arrow' : ''" @click="leaderSelect" style="display: flex; justify-content: space-between;">
					  <view class="content" style="display: flex; align-items: center;">
					    <text class="">负责人</text>
					  </view>
					  <view class="action" style="display: flex; align-items: center;">
					    <text class="text-grey text-sm">{{leader.name}}</text><text class="cuIcon-right"></text>
					  </view>
					</view>
					
					<view class="cu-form-group">
						<text>任务周期： </text>
						<view>
							<xp-picker @confirm="StartDate" :year-range="yearRange" v-if="this.staff.id == this.task.creatStaffId"> {{task.startTime}} </xp-picker>
						</view>
						<view class="" v-if="this.staff.id != this.task.creatStaffId">
							{{task.startTime}}
						</view>
						<view>
							<xp-picker @confirm="EndDate" :year-range="yearRange" v-if="this.staff.id == this.task.creatStaffId"> {{task.endTime}}</xp-picker>
						</view>
						<view class="" v-if="this.staff.id != this.task.creatStaffId">
							{{task.startTime}}
						</view>
					</view>
					<view class="cu-form-group">
						<view class="title">类型选择</view>
						<picker @change="PickerChange" :value="index" :range="picker" :disabled="this.staff.id != this.task.creatStaffId">
							<view class="picker">
								{{index>-1?picker[index]:'请选择任务类型'}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group">
						<view class="title">级别选择</view>
						<picker @change="PickerChangeLevel" :value="indexLevel" :range="level" :disabled="this.staff.id != this.task.creatStaffId">
							<view class="picker">
								{{indexLevel>-1?level[indexLevel]:'请选择任务级别'}}
							</view>
						</picker>
					</view>
					<view class="cu-form-group" @click="toggle('bottom')" >
						<text>任务进度：</text>
						<view class="progress-box" style="width:40%;">
							<progress :percent="task.taskProgress" show-info stroke-width="5" />
						</view>
					</view>
					
					<view class="cu-form-group" :class="menuArrow ? 'arrow' : ''" @click="selectStaff" style="display: flex; justify-content: space-between;">
					  <view class="content" style="display: flex; align-items: center;">
					    <text class="">参与人</text>
					  </view>
					  <view class="action" style="display: flex; align-items: center;">
					    <view class="cu-avatar-group" v-for="item in ids" :key="item.id" style="padding: 0;">
					      <view class="cu-avatar round sm" :style="{ 'background-image': 'url(' + item.avatar + ')' }" style="margin-left: -10px;"></view>
					    </view>
					    <text class="text-grey text-sm">{{ ids.length }} 人</text>
					  </view>
					</view>
					
					<div class="container" style="margin-top: 8px;padding-left: 12px;">
					  <div class="left">
					    <text class="label">任务详情：</text>
					  </div>
					  <div class="right" >
						  <textarea v-model="task.taskDetail" placeholder="请输入文本" class="textarea" maxlength="-1" style="padding-top:3px;" :disabled="this.staff.id != this.task.creatStaffId"></textarea>
					  </div>
					</div> 
					  
					  <view>
					     <uni-section title="上传附件" type="line" style="margin-top: 5px;margin-left: 10px;">
					       <view class="example-body" style="margin-top: 5px;margin-left: 10px;">
					         <uni-file-picker 
					  		   :limit="20"
					  		   fileMediatype="all"
					  		   mode="grid"
					  		   @select="select"
					  		   @progress="progress"
					  		   @success="success"
					  		   @fail="fail"
					  		   @delete="delFile(item)"
					  		 ></uni-file-picker>
					       </view>
					     </uni-section>
					  	<!-- <button @click="select(e)">上传文件</button> -->
					  	 <div class="file-list">
					  		  <div v-for="(file, index) in listFiles" :key="index" class="file-item">
					  			<div class="file-actions">
					  			  <view style="display: flex; justify-content: space-between;
					  			  margin-top: 8px;margin-bottom: 8px;border-radius: 5px;border: 1px solid gainsboro;padding: 10px;">
					  				<view style="margin-right: 5px;">
					  				  {{ file.name }}
					  				</view>
					  				<view class="" style="display: flex; justify-content: space-between;">
					  					<view class="cuIcon-down" style="font-size: 18px;margin-right: 10px;" @click="downloadFile(index)"></view>
					  					<view class="cuIcon-close" style="font-size: 18px;" @click="delFile(index)"></view>
					  				</view>
					  			  </view>
					  			</div>
					  		  </div>
					  		</div>
					   </view>
					   
					   <div class="button-row" >
					     <button class="update-button" @click="updateTask" style="font-size: 13px;height: 35px;width: 100px;" v-if="task.creatStaffId == staff.id">确认提交</button>
					     <!-- <button class="update-button" @click="completeTask" style="font-size: 13px;height: 35px;width: 100px;" v-if="!task.states && task.creatStaffId != staff.id">完成任务</button> -->
					     <button class="update-button" @click="completeTask" style="font-size: 13px;height: 35px;width: 100px;" v-if="!task.states">完成任务</button>
					     <button class="update-button" @click="reminderTask" style="font-size: 13px;height: 35px;width: 100px;" v-if="task.creatStaffId == staff.id && !task.states">一键提醒</button>
					     <button @click="delTask" style="font-size: 13px;height: 35px;width: 100px;" v-if="task.creatStaffId == staff.id">删除任务</button>
					   </div>
					   
					<view class="cu-form-group" >
						评论
					</view>
						
					<view class="parent-container" >
						<view class="" style="margin-bottom: 30px;">
							 <!-- 任务详情 -->
							<view class="cu-form-group" v-if="task.comment != null" v-for="e in task.comment" @click="delComment(e)" >
								<div class="comment-wrapper">
									<view class="" >
										<image :src="e.staff.avatar" class="avatar" style="width: 40px; height: 40px; border-radius: 50%; float: left; margin-right: 10px;float: left;"></image>
									</view>
								</div>
								<view class="title" v-if="e != null" style="width: 100%;height: auto;word-wrap: break-word;height: auto;line-height:unset">{{e.staff.name}}： {{e.content}}</view>
								<view class="" v-if="e == null" style="">{{e.staff.name}}： {{e.content}}</view> 
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		
		<view class="bg-white" v-if="TabCur === 1" style="width: 100%;">
			<view class="cu-form-group">
				<text>负责人评价：</text>
				<l-starRate v-model="task.myStart"  :disabled="task.staffId != staff.id"></l-starRate>
			</view>
			<view class="cu-form-group" style="margin-top: auto;">
				<text>领导评价：</text>
				<l-starRate v-model="task.leaderStart" :disabled="task.creatStaffId != staff.id"></l-starRate>
			</view>
			<button style="margin-top: 10px;" @tap="successEvaluation">完成评价</button>
		</view>
		
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff" @change="change" >
			<view style="text-align: center; font-size: 20px;display: flex;justify-content: space-between;" class="margin-top margin-bottom">
				<view class="" style="margin-left: 40rpx;" @tap="cancleModal">
					关闭
				</view>
				<view class="" style="margin-right: 40rpx;color: blue;" @tap="confirmModal">
					确定
				</view>
			</view>
			
			<view class="cu-form-group" :class="{ 'popup-height': type === 'left' || type === 'right' }" style="height: 150px;">
				 <text>当前进度值：</text>
				 <input type="number" v-model="inputValue" @input="updateSliderValue" style=""/>
				 <slider class="progress-slider" :value="currentProgress" @change="onProgressChange" style="width: 30%;padding-left: 10px;padding-right: 20px;"/>
				 <view class="progress-indicator" style="padding-right: 10px;">{{ currentProgress }}%</view>
			</view>
			
		</uni-popup>

		<popup-layer ref="popupRef" :direction="'top'" > <!-- 设置弹出层的高度 -->
			<view style="text-align: center; font-size: 20px;" class="margin-top margin-bottom" @tap="chengeCycle">{{ cycle.name }}(一个OKR只能选中一项)</view>
		  <!-- 为弹出层内容容器添加滚动条样式 -->
		  <view class="content bg-gray" style="overflow-y: auto;height: 450px;padding: unset;font-size: 11px;"> <!-- 添加样式以启用垂直滚动 -->
						<view class="custom-view" style="margin: 10px;" v-for="(item, index) in okrList" :key="index">
							<view style="border-bottom: 1px solid;">
								<view class="" style="display: flex; justify-content: space-between; align-items: center;background-color: white;">
								  <view class="title bg-white" style="font-size: 20px; padding: 10px;">
									{{ item.name }}
								  </view>
								</view>
								<div class="item-container bg-white" style=" display: flex; block;padding: 10px;">
								  <div style="display: flex; align-items: center;">
									<div>
									  负责人：{{item.leaderName}}，进度：
									</div>
									<div style="flex: 1;">
									  <liu-progressbar :textInside="false" :progress="item.progress" color="#333333" :height="'10rpx'" style="width: 300rpx;"/>
									</div>
								  </div>
								</div>
							</view>
							<view class="bg-white" style=" block;padding: 10px;" v-for="(kr, index2) in item.subOkrList" :key="index2" >
								<view :class="{ selected: kr.selected }" @click="selectKR(kr,index,index2)" style="display: flex; justify-content: space-between; align-items: center;background-color: white;">
									<view class="title" style="display: block;">
										{{ kr.content }}：{{ kr.name }}
									</view>
									<div :class="{ 'circle': true, 'selected': kr.selected }">
									  <div class="check-mark" v-if="kr.selected">&#10003;</div>
									</div>
								</view>
							</view>
						</view> 
		  </view>
					<view class="button-container" style="display: flex;">
						<button class="" style="font-size: 15px;width: 200px;flex: unset;height: 40px;border-radius: 8px;" @click="cancleSelcct">取消</button>
						<button class="confirm-button" style="border-radius: 8px;font-size: 15px;width: 200px;flex: unset;height: 40px;background-color: blue;color: white;" @click="comsumSelect">确定</button>
					</view>
		</popup-layer>
		
		<popup-layer ref="cyclePopupRef" :direction="'top'"> <!-- 设置弹出层的高度 -->
		<view style="text-align: center; font-size: 20px;" class="margin-top margin-bottom">周期选择</view>
		  <!-- 为弹出层内容容器添加滚动条样式 -->
		  <view class="content bg-gray" style="overflow-y: auto;height: 350px;"> <!-- 添加样式以启用垂直滚动 -->
			<view class="" v-for="(item, index) in cycleList" :key="index">
			  <view class="cu-form-group margin-top" @click="selectCycle(item)">
			  	<view class="title">
					{{item.name}}
					<span v-if="item.endTime > currentTime">(进行中)</span>
					<span v-else>(结束)</span>
				</view>
			  </view>
			</view>
		  </view>
		</popup-layer> 
		
		<!-- 底部输入框，用来评价当前任务 -->
		  <view class="flex-container bg-white" v-if="TabCur === 0">
			<input
			  type="text"
			  v-model="commentMessage"
			  placeholder="请输入消息"
			  class="flex-item input-box"
			  @focus="keyboardVisible = true"
			  @blur="keyboardVisible = false"
			/>
			<button class="flex-item send-button" @click="sendMessage"  style="font-size: 13px;">发送</button>
		  </view> 
	</view>
</template>

<script>
	import Viewer from 'viewerjs';
	import request from '../../common/request';
	import common from 'common/common.js';
	import xweek from 'components/junkj-xweek/xweek.vue';
	import MessageSender from '@/utils/sendMessage.js';
	import popupLayer from '../../components/popup-layer/popup-layer.vue';
	export default {
		components: {
			xweek,
			},
		data() {
			return {
				yearRange: [2020,2050],
				//上传测试
				listFiles: [],
				imageStyles: {
					width: 64,
					height: 64,
					border: {
						radius: '50%'
					}
				},
				listStyles: {
					// 是否显示边框
					border: true,
					// 是否显示分隔线
					dividline: true,
					// 线条样式
					borderStyle: {
						width: 1,
						color: 'blue',
						style: 'dashed',
						radius: 2
					}
				},
				// 滑动导航栏
				TabCur: 0,
				scrollLeft: 0,
				modules:[
					{"name": "任务详情"},
					{"name": "完成评价"},
				],
				// cs
				type: 'center',
				msgType: 'success',
				messageText: '这是一条成功提示',
				value: '',
				// 评论框
				commentMessage: '', // 用户输入的消息
				keyboardVisible: false, // 是否显示键盘
				
				menuArrow: '',
				// 两个选择框
				index: -1,
				indexLevel: -1,
				picker: ['每日任务', '每周任务', '月度任务','季度任务','年度任务','单次任务'],
				level: ['最高', '较高', '普通','较低'],
				
				// 修改进度条的底部弹框显示
				modalVisible: false,
				// 可拖动进度条
				currentProgress: 0, // 当前值
				inputValue: 0,
				showAlignment :true,
				task:{},
				updateShow:false,
				areaTxt: undefined,
				modalName: null,
				taskId: '',
				oldTask:{},
				ids: [],
				staff :{},
				kr:{name:''},
				
				okrList:[],
				cycleList:[],
				cycle: {},
				okr: {},
				leader:{name:''},
				cycleId:'',
				// 文件名
				fileNameDoc:'',
				// 文件路径
				tempFilePath:'',
				// 文件的string
				fileNames:'',
				sure: false,
				complateSates: false,
			}
		},
		// 从上个页面获取数据
		onLoad(options){
			this.taskId = options.id;
			console.log(this.taskId)
			if(options.task){
				this.oldTask = JSON.parse(decodeURIComponent(options.task));
				if(this.oldTask.cardId){
					this.showAlignment = false;
				}
				this.taskId = this.oldTask.id;
			}
			this.getAllCycle();
			this.getTaskById();
			this.staff = uni.getStorageSync("staff");
		},
		onShow() {
			var ids = uni.getStorageSync("ids");
			if(ids[0]){
				this.ids = ids;
			}
			var leader = uni.getStorageSync("leader");
			if(leader.id){
				this.leader = leader;
			}
		},
		computed: {
		    currentTime() {
				const currentDate = new Date();
				return this.formatDate(currentDate); // 获取当前时间
		    },
		},
		created() {
		    // 在组件创建时添加 popstate 事件监听器
		    window.addEventListener('popstate', this.handlePopstate);
		  },
		  destroyed() {
		    // 在组件销毁时移除 popstate 事件监听器，以防止内存泄漏
		    window.removeEventListener('popstate', this.handlePopstate);
		  },
		methods: {
			// 点击取消
			cancleSelcct(){
				this.$refs.popupRef.close();
			},
			// 点击确定
			comsumSelect(){
				this.$refs.popupRef.close();
			},
			// 检查是否是创建人
			isCreatStaff(){
				if(this.staff.id != this.task.creatStaffId){
					return true;
				} else {
					return false;
				}
			},
			// reminderTask 一键提醒完成任务
			reminderTask(){
				var _this = this;
				request({
					url: common.api_base_url+'/task/reminderTask/' + _this.task.id,
					data:{
					},
					header:{
					},
					method: 'GET',
					success: res => {
						if(res.data.success){
							uni.showToast({
								title: "已提醒",
								duration: 2000,
								icon:"success"
							})
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000,
								icon:"error"
							})
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 完成任务
			completeTask(){
				console.log(this.task)
				this.task.states = true;
				var _this = this;
				uni.request({
					url: common.api_base_url+'/task/changeStates',
					data:{
						"task": _this.task
					},
					header:{
					},
					method: 'PUT',
					success: res => {
						if(res.data.success){
							uni.showToast({
								title: "完成任务",
								duration: 2000,
								icon:"success"
							})
							_this.getTaskById();
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000,
								icon:"error"
							})
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			successEvaluation(){
				let _this = this;
				request({
					url: common.api_base_url+'/task/successEvaluation',
					data:{
						"taskId":_this.task.id,
						"myStart":_this.task.myStart,
						"leaderStart":_this.task.leaderStart,
					},
					method: 'POST',
					success: res => {
						uni.showToast({
							title:"完成评价",
							icon:"success"
						})
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 收集端上传文件
			// select(){
			// 	  // 显示的数组
			// 	  // var item ={
			// 		 //  name: e.tempFiles[0].name,
			// 	  // }
			// // 	  this.listFiles.push(item)
			// // 	  this.fileNameDoc = e.tempFiles[0].name;
			// // 	  this.filePathDoc = e.tempFiles[0].path;
			// // 	  this.filePathDoc = this.filePathDoc.split("/")[3];
				  
			// // 	  if(this.listFiles.length > 0){
			// // 		this.fileNames = this.listFiles.map(e=>e.name).join(",");
			// // 	  }
			
			// 	var _this = this;
			// 	wx.chooseImage({
			// 	  count: 1, // 一次只能选择一个文件
			// 	  formData: {
			// 		  rbacToken: uni.getStorageSync('rbacToken'),
			// 		  date: new Date().getTime(),
			// 		  id: _this.task.id,
			// 		  additionalData: _this.fileNames, // 添加额外的数据
			// 		},
			// 	  success: function (e) {
			// 		const tempFilePath = e.tempFilePaths[0];
			// 		// 调用上传文件的API
			// 		wx.uploadFile({
			// 		  url: common.api_base_url + '/uploadFile', // 上传文件的后端接口
			// 		  filePath: tempFilePath,
			// 		  name: e.tempFiles[0].originalFileObj.name, // 与后端接口约定的文件字段名称
			// 		  success: function (e) {
			// 			// 文件上传成功后的处理
			// 		  },
			// 		  fail: function (err) {
			// 			// 文件上传失败后的处理
			// 		  }
			// 		});
			// 	  }
			// 	});
			// },
			
			// 电脑端下载文件
			downloadFile(selectIndex) {
				var item = this.listFiles[selectIndex];
				this.fileNameDoc = item.name;
				
				// var url = common.api_base_url + "/downFile/" + this.filePathDoc; //平时测试 
				var url = common.api_base_url + "/downFile/" + this.fileNameDoc; // 上服务器
				var _this = this;
				uni.downloadFile({
					url: url,
					success: res => {
						if (res.statusCode === 200) {
							let index = url.lastIndexOf(".");
							let suffix = url.substr(index+1);
							// 打开文件
							// uni.openDocument({
							// 	filePath: res.tempFilePath,
							// 	fileType: suffix,
							// 	showMenu: true, // 右上角菜单，可以进行分享保存
							// 	success: function(file) {
							// 		console.log("file-success", file)
							// 	},
							// 	fail() {
							// 		console.log("预览失败")
							// 	}
							// })
							wx.openDocument({
								filePath: res.tempFilePath,
								fileType: suffix,
								showMenu: true, // 右上角菜单，可以进行分享保存
								success: function(file) {
								},
								fail() {
								}
							})
						}
					}
				})
			},
			// 删除测试
			delFile(index){
				var item = this.listFiles[index];
				this.fileNameDoc = item.name;
				
				this.listFiles.splice(index, 1);
				
				if(this.listFiles.length > 0){
					this.fileNames = this.listFiles.map(e=>e.name).join(",");
				}
				if(this.listFiles.length == 0){
					this.fileNames = null;
				}
				var delItem = {
					name: this.fileNameDoc,
					id: this.task.id,
					fileNames: this.fileNames
				}
				var _this = this;
				request({
					url: common.api_base_url+'/delFile',// 上服务器
					// url: common.api_base_url+'/delFile/' + _this.filePathDoc, // 测试
					data:{
						itedelItem: delItem
					},
					method: 'POST',
					success: res => {
						
						if(res.data.success){
							_this.listFiles.slice(item);
						}
						if(!res.data.success){
							_this.listFiles.push(item);
						}
						// 文件不存在
						if(res.data.code == -20){
							_this.listFiles.splice(index, 1);
							uni.showToast({
								title:res.data.message,
								icon:"error"
							})
						}
						
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 测试文件上传
			select(e) {
				// 显示的数组
				var item ={
					name: e.tempFiles[0].name,
				}
				this.listFiles.push(item);
				this.fileNameDoc = e.tempFiles[0].name;
				this.filePathDoc = e.tempFiles[0].path;
				this.filePathDoc = this.filePathDoc.split("/")[3];
				if(this.listFiles.length > 0){
					this.fileNames = this.listFiles.map(e=>e.name).join(",");
				}
				if(this.listFiles.length == 0){
					this.fileNames = e.tempFiles[0].name;
				}
				let _this = this;
				let fileSize = e.tempFiles[0].size;
				uni.uploadFile({
					url: common.api_base_url + '/uploadFile', //真实的接口地址
					filePath: e.tempFiles[0].path,
					name: 'file',
					formData: {
					  rbacToken: uni.getStorageSync('rbacToken'),
					  date: new Date().getTime(),
					  id: _this.task.id,
					  additionalData: _this.fileNames, // 添加额外的数据
					  staffName: _this.staff.name,
					},
					success(res) {
						var data = JSON.parse(res.data);
						// 有重复名
						if(data.code == -1){
							uni.showToast({
								title:data.message,
								icon:"error"
							})
						}
						// 不成功
						if(!data.success){
							_this.listFiles =  _this.listFiles.slice(0 ,-1);
						}
					}
				
				})
			},
			// 监听事件
			handlePopstate(event) {
				// 在这里执行与从上一个页面返回到本页面相关的操作
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				// 监听返回上个页面 pages/okrs/addOkr
				if (currentPage.route === 'pages/showList/taskDetail') {
					var ids = uni.getStorageSync("ids");
					this.ids = ids;
					var leader = uni.getStorageSync("leader");
					if(leader.id){
						this.leader = leader;
					}
				}
			},
			// 点击显示任务详情还是评论
			tabSelect(e) {
				var num = e.currentTarget.dataset.id;
				if(num == 1 && !this.sure ){
					uni.showModal({
						content:"请完成任务在进行评价"
					})
					return;
				} else{
					this.TabCur = num
					return;
				}
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
			},
			// 选择周期
			selectCycle(cycle) {
				this.cycle = cycle;
				this.okrList =  this.okrMap[this.cycle.id];
				this.$refs.cyclePopupRef.close();// 或者 boolShow = false
			},
			// 选中对标kr
			selectKR(selectedKR, index ,subOkrList) {
				if(selectedKR.selected){
					this.okr.selected = false;
					selectedKR.selected = false;
					this.okr = {};
				} else{
					this.okr.selected = false;
					selectedKR.selected = true;
					this.okr = selectedKR;
				}
			},
			// 获取当前周期所有的okr
			getOkrBycycleId(){
				var _this = this;
				request({
					url: common.api_base_url+'/okr/getAllOkrGroupBycycleId/',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.okrMap = res.data;
						_this.okrList = _this.okrMap[_this.cycle.id];
						_this.next();
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 点击开启周期选择弹框
			chengeCycle(){
				this.$refs.cyclePopupRef.show(); // 或者 boolShow = rue
			},
			// 点击开启KR选择弹框
			selectAlignment(){
				if(this.isCreatStaff()){
					return;
				}
				if(this.okrMap == undefined){
					this.getOkrBycycleId();
				} else{
					this.next();
				}
			},
			next(){
				// 存在说明有对标关键结果
				if(this.okr.cycleId){
					this.cycleId = this.okr.cycleId;
					this.cycle = this.cycleList.find(e => e.id == this.okr.cycleId);
					this.okrList = this.okrMap[this.cycleId];
					// var okr =  this.okrListfind(e=> e.subOkrList == this.okr.id);
					var self = this; // 保存对外部this的引用
					
					this.okrList.forEach(function(item) {
					  item.subOkrList.forEach(function(e) {
					    if (e.id == self.okr.id) {
					      e.selected = true;
						  self.okr = e;
					    }
					  });
					});
					
					// okr.selected = true;
				} else{
					this.cycle = this.cycleList[0];
					this.okrList = this.okrMap[this.cycle.id];
				}
				this.$refs.popupRef.show(); // 或者 boolShow = rue
			},
			// 获取所有周期
			getAllCycle(){
				var _this = this;
				request({
					url: common.api_base_url+'/cycle',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.cycleList = res.data;
						_this.cycle = _this.cycleList[0];
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			
			// 选中负责人
			leaderSelect(){
				if(this.isCreatStaff()){
					return;
				}
				uni.navigateTo({
					url:'/pages/addTask/leaderStaff?leader='+ encodeURIComponent(JSON.stringify(this.leader)),
				})
			},
			// 选择参与人员
			selectStaff(){
				if(this.isCreatStaff()){
					return;
				}
				// 选中了之后，回显
				uni.navigateTo({
					url:'/pages/addTask/selectStaff?ids='+ encodeURIComponent(JSON.stringify(this.ids)),
				})
			},
			
			change(e) {
				console.log('当前模式：' + e.type + ',状态：' + e.show);
			},
			// 任务条点击框
			toggle(type) {
				if(this.isCreatStaff()){
					return;
				}
				this.type = type;
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				if(this.complateSates){
					uni.showToast({
						title:"任务已完成，请勿修改",
						icon:"error"
					})
					return;
				}
				this.$refs.popup.open(type);
				this.currentProgress = this.task.taskProgress;
				this.inputValue = this.task.taskProgress;
			},
			// 删除任务
			delTask(){
				let _this = this;
				uni.showModal({
					title: '删除任务',
					content: '您确定要删除这条任务吗？',
					success: function (res) {
						if (res.confirm) {
							request({
								url: common.api_base_url+'/task/' + _this.task.id,
								data:{
								},
								header:{
								},
								method: 'DELETE',
								success: res => {
									uni.navigateBack({
										delta: 1,
										// success: function () {
										// 	const pages = getCurrentPages(); //获取当前页面栈
										// 	const prevPage = pages[pages.length - 1]; //获取上一个页面实例对象
											
										// 	const options = {
										// 	 projectId: _this.oldTask.projectId,
										// 	  // 添加其他需要传递的参数
										// 	};
										// 	prevPage.onLoad(options); //调用上一个页面的onLoad方法
										// }
									});
								},
								fail: function(e) {
									uni.showToast({
										title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
										icon:"loading"
									})
								},
							});
						} else if (res.cancel) {
							res.cancel = true;
						}
					}
				});
			},
			// 开始时间
			StartDate(e) {
				this.task.startTime = e.value
			},// 结束时间
			EndDate(e) {
				this.task.endTime = e.value
			},
			
			// 评论框发送
			 sendMessage() {
			  if (this.commentMessage.trim() !== '') {
					const userId = this.staff.userId;
					const userIdsSet = new Set(this.task.staffList.map(staff => staff.userId));
					userIdsSet.delete(userId);
				    // 将 Set 转换为数组
				    const uniqueUserIds = Array.from(userIdsSet);
					var _this = this;
					request({
						url: common.api_base_url+'/comment',
						data:{
							"taskId":_this.task.id,
							"staffId":_this.task.staffId,
							"content":_this.commentMessage,
							"leadId": _this.staff.id,
						},
						header:{
						},
						method: 'PUT',
						success: res => {
							var descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您的任务有新的评论，请点击查看</div><div class=\"highlight\">评论人："+ _this.staff.name +"，任务名称："+ _this.task.taskName +"</div>";
							MessageSender.sendMessage(uniqueUserIds.join(","), descript)
							  .then(response => { 
								console.log('Message sent successfully:', response);
								// 在这里可以处理发送成功的逻辑
							  })
							  .catch(error => {
								console.error('Error sending message:', error);
								// 在这里可以处理发送失败的逻辑
							  });
							_this.getTaskById();
						},
						fail: function(e) {
							uni.showToast({
								title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
								icon:"loading"
							})
						},
					});
				// 清空输入框
				this.commentMessage = '';
			  } else{
				  uni.showToast({
				  	title:"内容不能为空",
				  	icon:"error"
				  })
			  }
			},
			
			// 单选任务类型
			PickerChange(e) {
				this.index = e.detail.value;
				this.task.taskType = this.picker[this.index];
			},
			// 单选任务级别
			PickerChangeLevel(e) {
				this.indexLevel = e.detail.value;
				this.task.taskLevel = this.level[this.indexLevel];
			},
			
			// 拖动进度条事件
			onProgressChange(event) {
			      this.currentProgress = event.mp.detail.value;
				  this.inputValue = event.mp.detail.value;
			    },
			// 输入进度条数字事件
			updateSliderValue() {
				if(this.inputValue > 100 || this.inputValue < 0 ){
					uni.showToast({
						title:"请输入0-100",
						icon:"error"
					})
					this.inputValue = this.task.taskProgress;
					this.currentProgress = this.task.taskProgress;
					return;
				}
			  this.currentProgress = this.inputValue;
			},
			
			// 点击弹出 修改进度条底部弹窗
			clickChangeProgress(progress){
				this.modalVisible = true;
				this.currentProgress = this.task.taskProgress;
				this.inputValue = this.task.taskProgress;
				// this.updateTask();
			},
			// 取消 修改进度条底部弹窗
			cancleModal() {
				this.$refs.popup.close();
			},
			// 提交 修改进度条底部弹窗
			confirmModal(){
				this.$refs.popup.close();
				this.modalVisible = false;
				this.task.taskProgress = this.inputValue;
				// this.updateTask();
			},
			// 修改任务
			updateTask(){
				// 如果没有负责人
				if(!this.leader.id){
					uni.showToast({
						title:"请选择负责人",
						icon:"error"
					})
					return;
				}
				// 参与人员id
				if(this.ids){
					this.task.ids = this.ids.map(item => item.id);
					const isContained = this.task.ids.includes(this.leader.id);
					if(!isContained){
						this.task.ids.push(this.leader.id);
					}
				} else{
					this.task.ids.push(this.leader.id);
				}
				this.task.leader = this.leader;
				if(this.okr){
					this.task.okr = this.okr;
				}
				if(this.task.taskProgress > 100 || this.task.taskProgress < 0){
					uni.showToast({
						title:"进度更新有误",
						icon:"error"
					})
					return;
				}
				if(this.listFiles.length > 0){
					this.task.annex = this.listFiles.map(e=>e.name).join(",");
				}
				
				var _this = this;
				request({
					url: common.api_base_url+'/task',
					data:{
						"task": _this.task
					},
					header:{
					},
					method: 'PUT',
					success: res => {
						uni.showToast({
							title:"修改成功",
							duration: 1000
						})
						// if(_this.ids){
						// 	// 去掉最后当前人员
						// 	_this.ids = _this.ids.filter(item => item.id !== _this.staff.id);
						// 	// _this.ids.pop();
						// 	// 如果还有
						// 	if(_this.ids.length > 0){
						// 		var touserTmp = _this.ids.map(item => item.userId);
						// 		var touser = touserTmp.join("|");
						// 		var descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的任务下发，请点击查看</div><div class=\"highlight\">任务发布人："+ _this.staff.name +"，任务名称："+ _this.task.taskName +"</div>";
						// 		MessageSender.sendMessage(touser, descript)
						// 		  .then(response => {
						// 			console.log('Message sent successfully:', response);
						// 			// 在这里可以处理发送成功的逻辑
						// 		  })
						// 		  .catch(error => {
						// 			console.error('Error sending message:', error);
						// 			// 在这里可以处理发送失败的逻辑
						// 		  });
						// 	}
						// }
						uni.navigateBack({
						  delta: 1, // 返回到添加页面
						});
						// location.reload();
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 评论弹窗确定
			confirmAdd(){
				var _this = this;
				request({
					url: common.api_base_url+'/comment',
					data:{
						"taskId":_this.task.id,
						"staffId":_this.task.staffId,
						"content":_this.areaTxt,
						// "leadId": _this.startDate,
					},
					header:{
					},
					method: 'PUT',
					success: res => {
						uni.showToast({
							title:"评论成功",
							duration: 1000
						})
						_this.getTaskById();
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
				this.areaTxt='';
			},
			// 评论输入框
			textareaAInput(e) {
				this.areaTxt = e.detail.value
			},
			// 删除评论
			delComment(e){
				if(e.staff.id == this.staff.id || this.task.creatStaffId == this.staff.id ){
					let _this = this;
					uni.showModal({
					    title: '删除评论',
					    content: '您确定要删除这条评论吗？',
					    success: function (res) {
					        if (res.confirm) {
								request({
									url: common.api_base_url+'/comment/' + e.id,
									data:{
									},
									header:{
									},
									method: 'DELETE',
									success: res => {
										_this.getTaskById();
									},
									fail: function(e) {
										uni.showToast({
											title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
											icon:"loading"
										})
									},
								});
					        } else if (res.cancel) {
								res.cancel = true;
					        }
					    }
					});
				}
			},
			// 获取单个task数据
			getTaskById(){
				var _this = this;
				request({
					url: common.api_base_url+'/task/' + _this.taskId,
					data:{
					},
					header:{
					},
					method: 'GET',
					success: res => {
						_this.task = res.data;
						if(_this.task.leader){
							_this.leader = _this.task.leader;
						}
						if(_this.task.okr){
							_this.okr = _this.task.okr;
						}
						// _this.oldTask.ids = _this.task.staffList.map(item => item.id);
						// 是否有选择的员工
						if(_this.task.staffList != null){
							// _this.oldTask.ids = _this.task.staffList.map(item => item.id);
							_this.ids = _this.task.staffList;
						}
						// 任务级别回显
						if(_this.task.taskLevel){
							_this.level.forEach((item,index)=>{
								if(item == _this.task.taskLevel){
									_this.indexLevel = index;
								}
							})
						}
						// 任务类型回显
						if(_this.task.taskType){
							_this.picker.forEach((item,index)=>{
								if(item == _this.task.taskType){
									_this.index = index;
								}
							})
						}
						if(_this.task.annex){
							_this.listFiles = _this.task.annex.split(",").map(function(name) {
							  return { name: name };
							});
						}
						if(_this.task.taskProgress == 100){
							_this.sure = true;
							_this.complateSates = true;
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 时间转换格式方法
			formatDate(date) {
			  const year = date.getFullYear();
			  const month = String(date.getMonth() + 1).padStart(2, '0');
			  const day = String(date.getDate()).padStart(2, '0');
			  return `${year}-${month}-${day}`;
			},
		},
		
	}
</script>

<style>
.progress-slider {
  width: 80%;
  margin: 20px auto;
}

.progress-indicator {
  text-align: center;
  font-size: 18px;
  color: #007bff;
}


/* cs */
.flex-container {
  display: flex;
  flex-direction: row; /* 垂直居中对齐 */
  position: fixed;
  bottom: 0;
  left: 0; /* 如果需要指定水平位置，可以根据需求调整 */
  width: 100%; /* 让元素铺满屏幕宽度 */
  background-color: #fff; /* 背景颜色，根据需求自行调整 */
  z-index: 1; /* 可选，用于控制元素的层叠顺序 */
}

.flex-item {
  border: 1px solid #ccc;
  margin: 5px;
  height: 25px; /* 设置元素的高度 */
}

.input-box {
 width: 80%;
}

.send-button {
  background-color: #007bff;
  color: white;
  border: none;
  cursor: pointer;
  line-height: 25px;
  white-space: nowrap;
}

/* 文本域样式 */
.textarea {
  width: 100%;
  height: 100px;
  border: none; /* 去掉边框 */
  padding: 10px;
  resize: vertical; /* 允许垂直调整文本域大小 */
  outline: none; /* 去掉焦点时的外边框 */
}

/* 去掉picker后面的 > */
#custom-picker::after {
  content: none;
}
/* 评论 */
.comment-wrapper {
    display: flex;
    align-items: center; /* 垂直居中对齐 */
    margin: 5px; /* 可以根据需要调整间距 */
}

.comment-text {
    flex-grow: 1; /* 文字部分占据剩余空间 */
}

.popup-content {
  max-height: 500px; /* 设置最大高度为400像素，根据需要调整 */
  overflow-y: auto; /* 如果内容溢出，允许垂直滚动 */
}

/* .selected {
  border: 2px solid red;
} */

.button-row {
  display: flex;
  justify-content: space-between; /* 使按钮均匀分布在一排 */
}


.update-button {
  background-color: #007bff; /* 设置修改提交按钮的背景颜色 */
  color: #fff; /* 设置修改提交按钮的文字颜色 */
  border: 1px solid #007bff; /* 设置修改提交按钮的边框样式 */
  
}

/* 鼠标悬停时的样式 */
button:hover {
  opacity: 0.8; /* 降低按钮的透明度以表示悬停状态 */
}

.parent-container {
   display: flex;
    flex-direction: column; /* 或 row，根据需要 */
  /* 其他Grid属性 */
}
	/* 导航栏 */
	.cu-item {
		text-align: center;
	  flex: 1; /* 设置每个元素的宽度为50% */
	}
	
	/* 导航栏固定一行 */
	.propertyBox{
			flex-flow: row;
			justify-content: flex-start;
			display: flex;
		}
		
	.container {
	  display: flex;
	  align-items: center;
	}
	
	.left {
		 align-self: flex-start;
	  flex: 1;
	  white-space: nowrap; /* 防止左侧文本自动换行 */
	}
	
	.right {
	  flex: 30; /* 右侧占比较大 */
	  word-wrap: break-word; /* 允许右侧文本自动换行 */
	}
.label {
  /* position: absolute; */
    top: 0; /* 将 "详情" 文本放在父元素的顶部 */
}

.circle {
	    width: 30px;
	    height: 30px;
	    border-radius: 50%;
	    background-color: #dcdcdc;
	    display: inline-flex;
	    align-items: center;
	    justify-content: center;
	    cursor: pointer;
	    margin-right: 10px;
	  }
	
	  .circle.selected {
	    background-color: #99cc99; /* Selected color */
	  }
	
	  .check-mark {
	    font-size: 24px;
	    color: #fff;
	  }

</style>
